package com.lu.servlet;

import com.lu.pojo.User;
import com.lu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "UserServlet",urlPatterns = {"/User"})
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        String opr = req.getParameter("opr");
        if ("add".equals(opr)) {
            String uname = req.getParameter("uname");
            String upassword = req.getParameter("upassword");
            int i = new UserServiceImpl().addOneUser(uname, upassword);
            if (i > 0) {
                out.print("<script>alert('注册成功!');location.href = 'index.jsp';</script>");
            } else {
                out.print("<script>alert('注册失败!');history.back();</script>");
            }
        } else if ("edit".equals(opr)) {
            int uid = Integer.parseInt(req.getParameter("uid"));
            String uname = req.getParameter("uname");
            String upassword = req.getParameter("upassword");
            User user = new User(uid, uname, upassword);
            int i = new UserServiceImpl().editOneUser(user);
            if (i > 0) {
                out.print("<script>alert('修改成功!');location.href = 'admin_1.jsp';</script>");
            } else {
                out.print("<script>alert('修改失败!');history.back();</script>");
            }
        } else if ("del".equals(opr)) {
            int uid = Integer.parseInt(req.getParameter("uid"));
            int i = new UserServiceImpl().delOneUser(uid);
            if(i>0){
                out.print("<script>alert('删除成功!');location.href = 'admin_0.jsp';</script>");
            }else {
                out.print("<script>alert('删除失败!');history.back();</script>");
            }
        }


        out.flush();
        out.close();
    }
}
